<template>
  <div class='container'>
    <el-dialog title="新增学科" width="30%" :visible="showDialog" @close="dialogFormH">
      <el-form ref="dataForm" :rules="ruleInline" :model="formData"
        style="margin-left:10px;">
        <el-form-item label="学科名字" prop="subjectName">
          <el-input placeholder="请输入学科名称" v-model="formData.subjectName" size="small" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
  <el-switch
    v-model="formData.isFrontDisplay"
    active-color="#13ce66"
    :active-value="1"
    :inactive-value="0"
    inactive-color="#ff4949">
  </el-switch>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="centerFn">确定</el-button>
        <el-button size="small" @click="dialogFormH">取消</el-button>
      </el-col>
    </el-row>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'subjects',
  props: {
    // 是否显示弹层
    showDialog: {
      type: Boolean
    },
    // 权限点所有数据
    originList: {
      type: Array,
      default: _ => []
    },
    // 用来区分是编辑还是添加
    isEdit: {
      type: Object,
      default: _ => {}
    },
    // 点击那行的名字
    data: {
      type: Object,
      default: _ => {}
    }
  },
  data () {
    // 校验权限标识
    const validCode = (rule, value, callback) => {
      // 添加时的校验名字不能重复
      let existCodeList = this.originList.map(item => item.subjectName)
      if (this.isEdit.text === '修改') {
        // 编辑时的校验: subjectName能取自己
        existCodeList = this.originList.filter(item => item.subjectName !== this.data.subjectName).map(item => item.subjectName)
      }
      existCodeList.includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    return {
      formData: {
        subjectName: '',
        isFrontDisplay: 1
      },
      // 表单验证
      ruleInline: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 弹层隐藏
    dialogFormH () {
      this.formData = {
        subjectName: '',
        isFrontDisplay: 1
      }
      this.$refs.dataForm.resetFields()
      this.$emit('update:showDialog', false)
    },
    // 点击确定的时候
    centerFn () {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          // 一定要先把值给父级元素传过去在清空
          this.$emit('comfirmEV', { ...this.formData })
          this.dialogFormH()
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
